package book;

import java.util.ArrayList;
import java.util.List;

public class BookList {
    // 保存每个书籍对象
    private static List<Book> books = new ArrayList<>();
    // 保存所有书籍名称，作为操作索引
    private static List<String> booksName = new ArrayList<>();
    // 静态代码块
    static {
        // 初始化操作
        books.add(new Book("水浒传","施耐庵",
                66.6,"武侠小说"));
        books.add(new Book("三国演义","罗贯中",
                77.7,"谋略小说"));
        books.add(new Book("西游记","吴承恩",
                88.8,"神话小说"));
        books.add(new Book("红楼梦","曹雪芹",
                99.9,"古典小说"));

        booksName.add("水浒传");
        booksName.add("三国演义");
        booksName.add("西游记");
        booksName.add("红楼梦");
    }

    /**
     * 判断是否存在要添加的书籍
     * @param booksName 书籍名称
     * @return 是否存在
     */
    public boolean isContains(String booksName) {
        return BookList.booksName.contains(booksName);
    }

    /**
     * 书是否被借走
     * @param bookName 书名
     * @return 是否借走
     */
    public boolean isBookBorrowed(String bookName) {
        Book book = findBook(bookName);
        assert book != null;
        return book.isBorrowed();
    }

    public void searchBook(String bookName) {
        Book book = findBook(bookName);
        System.out.println(book);
    }

    /**
     * 添加书籍
     * @param book 书籍名称
     */
    public void addBook(Book book) {
        books.add(book);
        booksName.add(book.getName());
    }

    /**
     * 打印书籍列表
     */
    public void printBook() {
        // 遍历Books数组
        for (Book book : books) {
            System.out.println(book);
        }
    }

    /**
     * 借书
     * @param bookName 书籍名称
     */
    public void borrowBook(String bookName) {
        Book book = findBook(bookName);
        assert book != null;
        book.setBorrowed(true);
    }

    private Book findBook(String b) {
        for (Book book : books) {
            if (book.getName().equals(b)) {
                return book;
            }
        }
        return null;
    }

    /**
     * 删除书籍
     * @param bookName 书籍名称
     */
    public void removeBook(String bookName) {
        Book book = findBook(bookName);
        books.remove(book);
        booksName.remove(bookName);
    }

    /**
     * 归还书籍
     * @param bookName 书籍名称
     */
    public void returnBook(String bookName) {
        Book book = findBook(bookName);
        assert book != null;
        book.setBorrowed(false);
    }

    /**
     * 更新书籍
     * @param bookName 书籍名称
     * @param price 书籍价格
     * @param type 书籍类型
     */
    public void updateBook(String bookName,double price,String type) {
        Book book = findBook(bookName);
        assert book != null;
        book.setPrice(price);
        book.setType(type);
    }
}
